package tools.Project3.Group3.s12cs342;

import java.io.InputStream;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;

import activities.project3.group3.s12cs342.AuthenticateActivity;
import activities.project3.group3.s12cs342.QuizMasterActivity;
import activities.project3.group3.s12cs342.R;
import activities.project3.group3.s12cs342.R.id;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class AsyncAuth extends AsyncTask <Void, Integer, String> {
	String url;
	@SuppressWarnings("rawtypes") ArrayList prams;
	Context context;
	EditText un;
	TextView error;
	private HttpPost httppost;
	private StringBuffer buffer;
	private HttpResponse response;
	private HttpClient httpclient;
	private InputStream inputStream;
	private byte[] data;
	Context c;
	
	@SuppressWarnings("rawtypes")
	public AsyncAuth(Context context, String url, ArrayList prams, Context c){
		this.url = url;
		this.prams = prams;
		this.context = context;
		un  = (EditText)((AuthenticateActivity) context).findViewById(R.id.usernameField);
		error = (TextView)((AuthenticateActivity) context).findViewById(R.id.errorLbl);
		this.c = c;
	}
	
	@Override
	protected String doInBackground(Void... params) {
		try {
			httpclient = new DefaultHttpClient();
			httppost = new HttpPost("http://cs346.cs.uwosh.edu/students/preram47/login.php");

			httppost.setEntity(new UrlEncodedFormEntity(prams));

			response = httpclient.execute(httppost);
			inputStream = response.getEntity().getContent();

			data = new byte[256];

			buffer = new StringBuffer();
			int len = 0;
			while (-1 != (len = inputStream.read(data))) {
				buffer.append(new String(data, 0, len));
			}

			inputStream.close();
		} catch (Exception e) {
			return e + "";
		}
		try {
			return buffer.charAt(0) + "";
		} catch (NullPointerException e) {
			return "S";
		}

	}

	protected void onPostExecute(String res){
		if(res.equals("L")){
			Intent ourIntent = new Intent(((AuthenticateActivity) context), QuizMasterActivity.class);
			((AuthenticateActivity) context).startActivity(ourIntent);
		}
		else
			Toast.makeText(((AuthenticateActivity) context), "Invalid username or password " , Toast.LENGTH_LONG).show();
	}

}
